//
//  JXEmojiViewLayout.m
//  Emoji_keyboard
//
//  Created by raymond on 16/7/5.
//  Copyright © 2016年 raymond. All rights reserved.
//

#define COL 7
#define ROW 3
#define margin 0

#import "JXEmojiViewLayout.h"

@interface JXEmojiViewLayout ()

/// layout属性数组
@property(nonatomic, strong)
    NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArr;

@property(nonatomic, assign) NSInteger totalPage;

@end

@implementation JXEmojiViewLayout

- (void)prepareLayout {
  [super prepareLayout];
  self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
  CGFloat contentWidth = self.collectionView.bounds.size.width;
  CGFloat contentHeight = self.collectionView.bounds.size.height;
  CGFloat itemWidth = (contentWidth - (COL + 1) * margin) / COL;
  CGFloat itemHeight = (contentHeight - (ROW + 1) * margin) / ROW;
  self.itemSize = CGSizeMake(itemWidth, itemHeight);
  self.minimumInteritemSpacing = margin;
  self.minimumLineSpacing = margin;
  self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)
layoutAttributesForElementsInRect:(CGRect)rect {
  return self.attributesArr;
}

- (NSMutableArray<UICollectionViewLayoutAttributes *> *)attributesArr {
  if (_attributesArr == nil) {
    _attributesArr = [NSMutableArray
        arrayWithCapacity:[self.collectionView numberOfItemsInSection:0]];
    // 用于记录组的起始页数
    unsigned int sectionPage = 0;

    for (int section = 0; section < [self.collectionView numberOfSections];
         ++section) {
      int page = 0;
      for (int i = 0; i < [self.collectionView numberOfItemsInSection:section];
           ++i) {
        NSIndexPath *indexPath =
            [NSIndexPath indexPathForItem:i inSection:section];
        UICollectionViewLayoutAttributes *attributes =
            [UICollectionViewLayoutAttributes
                layoutAttributesForCellWithIndexPath:indexPath];
        page = i / (COL * ROW);
        CGFloat itemX =
            (self.itemSize.width + self.minimumInteritemSpacing) * (i % COL) +
            margin +
            [UIScreen mainScreen].bounds.size.width * (page + sectionPage);
        CGFloat itemY = (self.itemSize.height + self.minimumInteritemSpacing) *
                            (i / COL - (page)*ROW) +
                        margin;
        attributes.frame =
            CGRectMake(itemX, itemY, self.itemSize.width, self.itemSize.height);
        [_attributesArr addObject:attributes];
      }
      page = page + 1;
      sectionPage += page;
    }
  }
  return _attributesArr;
}

@end
